package ifly

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/spf13/viper"
)

func (r *Ifly) NewTranslation(slugs ...string) *Translation {
	slug := "default"
	if len(slugs) > 0 {
		slug = slugs[0]
	}
	appId := viper.GetString(fmt.Sprintf("org.ifly.translation.%s.appId", slug))

	return &Translation{
		org:   r,
		appId: appId,
	}
}

type Translation struct {
	org   *Ifly
	appId string
}

func (r *Translation) Text(text, languageFrom, languageTo string) string {
	tt, _ := json.Marshal(map[string]interface{}{
		"common": map[string]interface{}{
			"app_id": r.appId,
		},
		"data": map[string]interface{}{
			"text": base64.StdEncoding.EncodeToString([]byte(text)),
		},
		"business": map[string]interface{}{
			"from": languageFrom,
			"to":   languageTo,
		},
	})

	return r.org.DoRequest("POST", "https", "itrans.xfyun.cn", "/v2/its", tt)
}
func (r *Translation) TextV1(text, languageFrom, languageTo string) string {
	tt, _ := json.Marshal(map[string]interface{}{
		"common": map[string]interface{}{
			"app_id": r.appId,
		},
		"data": map[string]interface{}{
			"text": base64.StdEncoding.EncodeToString([]byte(text)),
		},
		"business": map[string]interface{}{
			"from": languageFrom,
			"to":   languageTo,
		},
	})

	return r.org.DoRequest("POST", "https", "itrans.xf-yun.com", "/v1/its", tt)
}
func (r *Translation) TextN(text, languageFrom, languageTo string) string {
	tt, _ := json.Marshal(map[string]interface{}{
		"common": map[string]interface{}{
			"app_id": r.appId,
		},
		"data": map[string]interface{}{
			"text": base64.StdEncoding.EncodeToString([]byte(text)),
		},
		"business": map[string]interface{}{
			"from": languageFrom,
			"to":   languageTo,
		},
	})

	return r.org.DoRequest("POST", "https", "ntrans.xfyun.cn", "/v2/ots", tt)
}

func generateSignature(host, date, httpMethod, requestUri, httpProto, digest, secret string) string {
	var signatureStr string
	if len(host) != 0 {
		signatureStr = "host: " + host + "\n"
	}
	signatureStr += "date: " + date + "\n"
	signatureStr += httpMethod + " " + requestUri + " " + httpProto + "\n"
	signatureStr += "digest: " + digest
	return hmacSign(signatureStr, secret)
}
func hmacSign(data, secret string) string {
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(data))
	encodeData := mac.Sum(nil)
	return base64.StdEncoding.EncodeToString(encodeData)
}
func signBody(data []byte) string {
	sha := sha256.New()
	sha.Write(data)
	encodeData := sha.Sum(nil)
	return base64.StdEncoding.EncodeToString(encodeData)
}
